package com.ldk.admin.controller;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.DateUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.enums.BillingMode;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.enums.TripStatus;
import com.ldk.framework.service.ICJTServiceTripService;
import com.ldk.framework.service.ICjtCityService;
import com.ldk.framework.service.ICjtRoadService;
import com.ldk.framework.service.ICjtSchedulService;
import com.ldk.framework.service.ICompanypermitService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IServiceTripCrewsService;

import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/citscheduel")
public class CjtScheduelController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "citscheduel";
    /**
     * 模块名称
     */
    private final String module = "城际通排班";

    @Autowired
    private ICjtCityService cjtCityService;

    @Autowired
    private ICjtRoadService cjtRoadService;

    @Autowired
    private ICjtSchedulService cjtSchedulService;
    @Autowired
    private ICJTServiceTripService cJTServiceTripService;
    @Autowired
    private IServiceTripCrewsService serviceTripCrewsService;
    @Autowired
    private ICompanypermitService companypermitService;
    @Autowired
    private IDriverService driverService;


    @RequestMapping("/list")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
        } else {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        }

        Calendar calendar = Calendar.getInstance();
        String startTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
        map.addAttribute("startTime", startTime);


        map.addAttribute("route", route);
        map.addAttribute("roadList", getRoadList());
        //操作日志
        //this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
        /*if (this.getRoleId(request) == 6) {
			return new ModelAndView("/cjt/listdict_sj");
		} else {
			return new ModelAndView("/cjt/listdict");
		}*/
        return new ModelAndView("/cjt/scheduellist");
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<CjtSchedul> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                 @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                                 @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
                                                 @RequestParam(value = "driverName", required = false, defaultValue = "") String driverName,
                                                 @RequestParam(value = "carNo", required = false, defaultValue = "") String carNo,
                                                 @RequestParam(value = "roadId", required = false, defaultValue = "0") Long roadId,
                                                 @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                                 HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        CjtSchedul query = new CjtSchedul();
        if (!TextUtils.isEmpty(driverName)) {
            query.setDriverName(driverName);
        }
        if (!TextUtils.isEmpty(carNo)) {
            query.setCarNo(carNo);
        }
        if (roadId > 0) {
            query.setRoadId(roadId);
        }
        if (!TextUtils.isEmpty(startTime)) {
            query.setTimeStr(startTime);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<CjtSchedul> result = cjtSchedulService.selectPageList("", query, pageable);

        LigerUIGridResult<CjtSchedul> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();
        return grid;
    }

    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);

        map.addAttribute("roadList", getRoadList());
        map.addAttribute("driverList", findBindDriverList());


        CjtSchedul model = new CjtSchedul();
        model.setTimeStr(DateUtil.DatetoString(new Date(), DateUtil.yyyyMMdd));

        return new ModelAndView("/cjt/scheduelinfo", "model", model);
    }

    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        CjtSchedul query = new CjtSchedul();
        query.setId(id);

        CjtSchedul model = cjtSchedulService.selectByKey("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + id, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("roadList", getRoadList());
        map.addAttribute("driverList", findBindDriverList());

        return new ModelAndView("/cjt/scheduelinfo", "model", model);
    }

    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") CjtSchedul model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            /*CjtSchedul query = new CjtSchedul();
            query.setRoadId(model.getRoadId());

            CjtSchedul exitObject = cjtSchedulService.selectOne("", query);
            if (exitObject != null) {
                rst.AddError(String.format("%s已经存在", model.getFromTo()));
                return new ModelAndView("redirect:/" + route + "/add");
            }*/
            if (TextUtils.isEmpty(model.getDriverOpenid())) {
                rst.AddError("请选择驾驶员");
                return new ModelAndView("redirect:/" + route + "/add");
            }
            /*List<DriverBindCar> list = driverService.findBindDriverList("");
            if(list!=null){
                for (DriverBindCar driverBindCar:list){
                    if(driverBindCar.getDriverOpenid().equals(model.getDriverOpenid())){
                        model.setCarId(driverBindCar.getVehicleId());
                        model.setCarNo(driverBindCar.getVehicleNo());
                        model.setDriverName(driverBindCar.getDriverName());
                    }
                }
            }*/
            Driver driver = driverService.getDriverByOpenId("", model.getDriverOpenid());
            if (driver != null) {
                model.setCarNo(driver.getCarNo());
                model.setDriverName(driver.getTrueName());
                model.setSeats(driver.getCarSeats());
                model.setHaveSeat(driver.getCarSeats() - 1);
            }
            model.setGoods(0);
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if (!TextUtils.isEmpty(model.getTimeStr())) {
                model.setTime(DateUtil.StringtoDate(model.getTimeStr(), DateUtil.yyyyMMdd).getTime() / 1000);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());
            model.setOperate(this.getAdminUserName(request).toString());
            this.insertOplog(request, module, "", "", "添加排班:" + model.getRoadName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
            long schedulId = cjtSchedulService.insertAndGetAutoIncrementId("", model, "id");
            if (schedulId > 0) {
                model.setId(schedulId);
                addOrUpdateServiceTrip(model);
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败，失败原因：" + e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") CjtSchedul model, RedirectAttributes redAttr, ModelMap map,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            /*CjtSchedul query = new CjtSchedul();
            query.setFromTo(model.getFromTo());

            CjtSchedul exitObject = cjtSchedulService.selectOne("", query);
            if (exitObject != null && exitObject.getId() != model.getId()) {
                rst.AddError(String.format("%s已经存在", model.getFromTo()));
                return new ModelAndView("redirect:/" + route + "/edit/{id}");
            }*/
            Driver driver = driverService.getDriverByOpenId("", model.getDriverOpenid());
            if (driver != null) {
                model.setCarNo(driver.getCarNo());
                model.setDriverName(driver.getTrueName());
                model.setSeats(driver.getCarSeats());
                model.setHaveSeat(driver.getCarSeats() - 1);
            }
            model.setGoods(0);
            if (model.getEnabled() == null) {
                model.setEnabled(false);
            }
            if (!TextUtils.isEmpty(model.getTimeStr())) {
                model.setTime(DateUtil.StringtoDate(model.getTimeStr(), DateUtil.yyyyMMdd).getTime() / 1000);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());
            model.setOperate(this.getAdminUserName(request).toString());
            this.insertOplog(request, module, "", "", "添加排班:" + model.getRoadName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = cjtSchedulService.updateByKey("", model);
            if (row > 0) {
                addOrUpdateServiceTrip(model);
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败，失败原因：" + e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/edit/{id}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setViewMode(map, ViewMode.View);
        CjtSchedul query = new CjtSchedul();
        query.setId(id);
        CjtSchedul model = cjtSchedulService.selectByKey("", query);
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("roadList", getRoadList());

        return new ModelAndView("/cjt/scheduelinfo", "model", model);
    }

    @ResponseBody
    @RequestMapping("/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        int row = 0;
        try {
            //操作日志
            CjtSchedul query = new CjtSchedul();
            query.setId(id);
            CjtSchedul dict = cjtSchedulService.selectByKey("", query);
            this.insertOplog(request, module, "", "", "删除:" + dict.getRoadName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            row = cjtSchedulService.deleteByKey("", query);
            if (row > 0) {
                cancelOrder(dict);
            }
        } catch (Exception e) {

        }
        if (row > 0) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }


    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }

    /**
     * 获取开通城市列表
     *
     * @return
     */
    private List<CjtCity> getCityList() {
        CjtCity query = new CjtCity();
        query.setEnabled(true);

        return cjtCityService.selectList("", query);
    }

    /**
     * 获取所有路线列表
     *
     * @return
     */
    private List<CjtRoad> getRoadList() {
        CjtRoad query = new CjtRoad();
        query.setEnabled(true);

        return cjtRoadService.selectList("", query);
    }

    /**
     * 获取所有路线列表
     *
     * @return
     */
    private List<DriverBindCar> findBindDriverList() {
        Driver query = new Driver();
        query.setServiceCodes(ServiceCode.CJT.getCode());


        List<DriverBindCar> list = driverService.findBindDriverList("");
        if (list != null && list.size() > 0) {
            for (DriverBindCar driverBindCar : list) {
                driverBindCar.setPhoneNo(driverBindCar.getDriverName() + "-" + driverBindCar.getPhoneNo());
            }
        }
        return list;
    }

    private void addOrUpdateServiceTrip(CjtSchedul cjtSchedul) {
        try {
            int insert = 1;//1更新  0 插入
            ServiceTrip qserviceTrip = new ServiceTrip();
            qserviceTrip.setSchedulId(cjtSchedul.getId());
            ServiceTrip entity = cJTServiceTripService.selectOne("", qserviceTrip);
            if (entity == null) {
                entity = new ServiceTrip();
                insert = 0;
            }
            CjtRoad query = new CjtRoad();
            query.setId(cjtSchedul.getRoadId());
            CjtRoad model = cjtRoadService.selectByKey("", query);
            if (model == null) {
                return;
            }
            String tripNo = SystemUtil.generateOrderNo(TripNoType.CJT.getPrefix());
            String time = DateUtil.longToStr(cjtSchedul.getTime() * 1000, "yyyy-MM-dd");
            Long lGoTime = SystemUtil.stringToSeconds(time + " " + cjtSchedul.getGoTime(), "yyyy-MM-dd HH:mm");

            entity.setTripNo(tripNo);
            entity.setServiceCode(ServiceCode.CJT.getCode());
            entity.setUserType(PlatformUserType.DRIVER_USER.getValue());
            entity.setOpenId(cjtSchedul.getDriverOpenid());
            entity.setRoadId(cjtSchedul.getRoadId());
            entity.setSchedulId(cjtSchedul.getId());
            entity.setStartLocation(model.getStartCity());
            //entity.setStartLon(startLon);
            //entity.setStartLat(startLat);
            entity.setEndLocation(model.getEndCity());
            //entity.setEndLon(endLon);
            //entity.setEndLat(endLat);
            entity.setGoTime(lGoTime);
            entity.setCarSeats(cjtSchedul.getSeats() - 1);
            entity.setCrewCount(0);
            entity.setCreateTime(SystemUtil.getAllSeconds());
            entity.setStatus(TripStatus.Accept.getValue());
            entity.setDistance(model.getMileage());
            entity.setDuration(0.0);
            entity.setHasAsign(false);
            entity.setHasComment(false);
            entity.setBillingMode(BillingMode.MakePrice.getValue());
            entity.setDriverOpenId(cjtSchedul.getDriverOpenid());
            entity.setCompanyId(model.getCompanyId());
            //entity.setAreaCode(model.getStartCode());
            entity.setRemark(model.getFromTo());
            //对费用进行四舍五入
            entity.setPayFee(model.getPrice());
            int row = 0;
            if (insert > 0) {
                row = cJTServiceTripService.updateByKey("", entity);
            } else {
                row = cJTServiceTripService.insert("", entity);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    private void cancelOrder(CjtSchedul cjtSchedul) {
        ServiceTrip qserviceTrip = new ServiceTrip();
        qserviceTrip.setSchedulId(cjtSchedul.getId());
        ServiceTrip entity = cJTServiceTripService.selectOne("", qserviceTrip);
        if (entity == null) {
            return;
        }
        int row = cJTServiceTripService.deleteByKey("", entity);
        if (row > 0) {
            ServiceTripCrews tripCrews = new ServiceTripCrews();
            tripCrews.setDriverTripNo(entity.getTripNo());
            tripCrews.setDriverOpenId(entity.getDriverOpenId());
            serviceTripCrewsService.delete("", tripCrews);
        }
    }


}
